import { local } from "@/utils/storage";
import { login, validate } from "@/api/user.api";
import router from "@/router";
import article from "@/router/article.router";
import {
  USER_LOGIN,
  SET_USER,
  SET_PERMISSION,
  USER_VALIDATE,
  USER_LOGOUT,
  ADD_ROUTE,
  SET_MENU_PERMISSION
} from "../action.types";

interface Auth {
  auth: string;
  id: number;
  name: string;
  path: string;
  pid: number;
  role: string;
  _id: string;
}
interface User {
  authList?: Auth[];
  avatar?: string;
  created?: string;
  gender?: number;
  name?: string;
  role?: string;
  status?: string;
  token?: string;
  updated?: string;
  username?: string;
  _id?: string;
}
interface State {
  user: User;
  hasPermission: boolean;
  menuPermission: boolean;
}

const filterRouter = (authList: any) => {
  const auths = authList.map((auth: any) => auth.auth);
  function filter(routes: any) {
    return routes.filter((route: any) => {
      if (auths.includes(route.meta.auth)) {
        if (route.children) {
          route.children = filter(route.children);
        }
        return route;
      }
    });
  }
  return filter(article);
};

const userState: State = {
  user: {},
  hasPermission: false,
  menuPermission: false
};
const getters = {
  user: (state: State): User => state.user
};
// TODO:actions代码可读性较差后期需要重构
const actions = {
  async [USER_LOGIN](_vuex: any, payload: any) {
    const { data } = await login(payload);
    _vuex.dispatch(SET_USER, { user: data, permission: true });
  },
  async [SET_USER](_vuex: any, _payload: any) {
    _vuex.commit(SET_USER, _payload.user);
    _vuex.commit(SET_PERMISSION, _payload.permission);
  },
  async [USER_VALIDATE](_vuex: any) {
    // 如果没token 就不用发请求了 肯定没登录
    if (!local.get("token")) return false;
    try {
      const result = await validate();
      _vuex.dispatch(SET_USER, { payload: result.data, permission: true });
      return true;
    } catch (e) {
      _vuex.dispatch(SET_USER, { payload: {}, permission: false });
      return false;
    }
  },
  async [USER_LOGOUT](_vuex: any) {
    _vuex.dispatch(SET_USER, { payload: {}, permission: false });
  },
  async [ADD_ROUTE](_vuex: any) {
    debugger;
    const authList = _vuex.state.user.authList;
    if (authList) {
      const routes = filterRouter(authList);
      const r: any = router;
      const route = r.options.routes.find((item: any) => item.path === "/manager");
      route.children = routes;
      router.addRoutes([route]);
      _vuex.commit(SET_MENU_PERMISSION, true);
    } else {
      _vuex.commit(SET_MENU_PERMISSION, true);
    }
  }
};
const mutations = {
  [SET_USER](state: State, payload: User) {
    state.user = payload;
  },
  [SET_PERMISSION](state: State, payload: boolean) {
    state.hasPermission = payload;
  },
  [SET_MENU_PERMISSION](state: State, has: boolean) {
    state.menuPermission = has;
  }
};

export default {
  namespaced: true,
  state: userState,
  getters,
  actions,
  mutations
};
